/*
 * @Author: 严晗 823841034@qq.com
 * @Date: 2023-10-17 17:00:00
 * @LastEditors: 严晗 823841034@qq.com
 * @LastEditTime: 2023-11-06 11:00:56
 * @FilePath: /yike-admin/Users/yanhan/vite-project/src/composables/useUser.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// compositionAPI 拆分页面上的js代码
import { ref, reactive } from 'vue'
import { toast, showModel } from '~/composables/utils'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

// 修改密码
export function useUpdatePassword() {
	const router = useRouter()
	const store = useStore()

	// 修改密码
	// 定义form表单里面的值
	const ruleForm = reactive({
		phone: store.state.auth.user.userInfo.phone,
		username: store.state.auth.user.userInfo.username,
		password: '',
		newpassword1: '',
		newpassword2: '',
	})
	// 定义校验规则
	const rules = reactive({
		password: [
			{
				required: true,
				message: '请输入旧密码',
				trigger: 'blur',
			},
		],
		newpassword1: [
			{
				required: true,
				message: '请输入新密码',
				trigger: 'blur',
			},
		],
		newpassword2: [
			{
				required: true,
				message: '请输入确认密码',
				trigger: 'blur',
			},
		],
	})

	// 双向绑定form表单的ref值
	const ruleFormRef = ref(null)
	// 绑定formDrawer组件的ref值
	const formDrawerRef = ref(null)
	// 通过 formDrawerRef 调用组件方法
	const openFormDrawer = () => formDrawerRef.value.open()

	// 点击登录按钮时触发
	const submitForm = () => {
		// 通过form表单的ref值进行校验
		if (!ruleFormRef.value) return
		ruleFormRef.value.validate((valid, fields) => {
			if (valid) {
				formDrawerRef.value.showLoading()
				store
					.dispatch('updatePassword', ruleForm)
					.then(() => {
						// 提示
						toast('修改密码成功')

						// 跳转到登录页
						router.push('/login')
					})
					.finally(() => {
						formDrawerRef.value.hideLoading()
					})
			} else {
				return false
			}
		})
	}

	return {
		ruleForm,
		rules,
		ruleFormRef,
		submitForm,
    formDrawerRef,
		openFormDrawer,
	}
}

// 退出登录
export function useLogout() {
	const router = useRouter()
	const store = useStore()
	// 退出登录系统方法
	const handleLogout = () => {
		showModel('退出系统, 是否继续?').then(() => {
			store.dispatch('logout').finally(() => {
				// 提示
				toast('退出登录成功')
				// 跳转回登录页
				router.push('/login')
			})
		})
	}
	return { handleLogout }
}
